﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Web.Security;

namespace DNA.Mvc
{
    public class WebMail
    {
        public static void Send(string displayName, string to, string subject, string body)
        {
            var webConfig = WebConfigurationManager.OpenWebConfiguration("~/web.config");
            var smtp = webConfig.GetSection("system.net/mailSettings/smtp") as SmtpSection;

            if (string.IsNullOrEmpty(to))
                throw new ArgumentNullException("to");

            if (smtp != null)
            {
                if (smtp.Network != null)
                {
                    var receivers = new List<string>();
                    var mail = new MailMessage();

                    if (to.IndexOf(",") > -1)
                    {
                        receivers.AddRange(to.Split(','));

                        for (int j = 0; j < receivers.Count;j++ )
                        {
                            var _member = Membership.GetUser(receivers[j]);

                            if (_member != null)
                            {
                                if (j == 0)
                                    mail.To.Add(_member.Email);
                                else
                                    mail.Bcc.Add(new MailAddress(_member.Email));
                            }
                        }
                    }
                    else
                    {
                        var toUser = Membership.GetUser(to);
                        if (toUser == null)
                        {
                            var existsUserName = Membership.GetUserNameByEmail(to);
                            if (!string.IsNullOrEmpty(existsUserName))
                                mail.To.Add(to);
                            else
                                return;
                        }
                        else
                            mail.To.Add(toUser.Email);
                    }

                    if (!string.IsNullOrEmpty(smtp.From))
                    {
                        if (string.IsNullOrEmpty(displayName))
                            mail.From = new MailAddress(smtp.From);
                        else
                            mail.From = new MailAddress(smtp.From, displayName);
                    }

                    mail.Subject = subject;
                    mail.Body = body;
                    mail.IsBodyHtml = true;

                    var smtpClient = new SmtpClient();
                    smtpClient.SendAsync(mail, null);
                }
            }

        }
    }
}
